package cn.ds.hbase.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.Set;

/**
 * 项目名称:hbase-learn<br>
 * 包名:cn.ds.hbase.config<br>
 * 用于:hbase-learn<br>
 * 创建时间:2019年03月15日<br>
 * 更新时间:2019年03月15日<br>
 *
 * @author :lds（创建人）<br>
 * @version :v1.0（版本号）<br>
 * @since jdk1.8
 */
@Configuration
@MapperScan(basePackages = PhoenixDataSourceConfig.PACKAGE,sqlSessionFactoryRef = "PhoenixSqlSessionFactory")
public class PhoenixDataSourceConfig {

    static final String PACKAGE = "cn.ds.hbase.**";
    static final String MAPPER_LOCATION = "classpath:mapper/hbase/*.xml";

    @Bean(name = "PhoenixDataSource")
    @Primary
    public DataSource phoenixDataSource() throws IOException{
        //加载配置文件
        final DefaultResourceLoader loader = new DefaultResourceLoader();
        try(final InputStream inputStream = loader.getResource("classpath:db.properties").getInputStream()) {
            final Properties confProperties = new Properties();
            confProperties.load(inputStream);
            final Properties dbProperties = new Properties();
            final Set<Object> keySet = confProperties.keySet();
            for (Object key : keySet) {
                if (key.toString().startsWith("datasource")){
                    dbProperties.put(key.toString().replace("datasource.",""),confProperties.get(key));
                }
            }
            final HikariDataSourceFactory factory = new HikariDataSourceFactory();
            factory.setProperties(dbProperties);
            return factory.getDataSource();
        }
    }

    @Bean(name = "PhoenixSqlSessionFactory")
    @Primary
    public SqlSessionFactory phoenixSqlSessionFactory(@Qualifier("PhoenixDataSource") DataSource dataSource) throws Exception {
        final SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        final DefaultResourceLoader loader = new DefaultResourceLoader();
        factoryBean.setConfigLocation(loader.getResource("classpath:mybatis-config.xml"));
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION));
        factoryBean.setSqlSessionFactoryBuilder(new SqlSessionFactoryBuilder());
        return factoryBean.getObject();
    }
}
